var app = getApp()
Page({
  data: {
    regionValue: [], //省市
    showRegion: false, //省市
    province_id: 0, //省
    city_id: 0, //市区
    district_id: 0, //乡镇
    province_name: '', //省
    city_name: '', //市区
    district_name: '', //乡镇
    town:'',
    town_id:'',
    id:null
  },
  //获取省市
  chooseRegion: function () {
    this.setData({
      showRegion: true,
    });
  },
  //获取省市
  emitHideRegion: function (e) {
    console.log("e" +JSON.stringify(e.detail.regionValue))
    this.setData({
      showRegion: e.detail.showRegion,
      regionValue: e.detail.regionValue,
      province_id: e.detail.regionValue[0].id,
      city_id: e.detail.regionValue[1].id,
      district_id: e.detail.regionValue[2].id,
      province_name: e.detail.regionValue[0].name,
      city_name: e.detail.regionValue[1].name,
      district_name: e.detail.regionValue[2].name,
      town:e.detail.regionValue[3].name,
      town_id:e.detail.regionValue[3].id,
      editId:false
    });
  },
  onLoad: function (e) {
    var that = this;
    console.log(e.type)
    that.GetAddress()
    if (e && e.type) {
      that.setData({
        operaType: e.type
      })
    }
    wx.getStorage({
      key: "curEditaddress",
      success: function (res) {
        console.log('编辑地址-----');
        console.log(res);
        // var region = [res.data.province, res.data.city, res.data.area];
        // region.push(res.data.province);
        // region.push(res.data.province)
        // region.push(res.data.province)

        that.setData({
          name: res.data.name,
          mobile: res.data.mobile,
          addressdetail: res.data.address,
          code: res.data.post,
          editId: res.data.id,
          curChooseAddress: res.data.pcda,
          curChooseLatitude: res.data.lat,
          curChooseLongitude: res.data.lng,
          isdefault: res.data.isdefault,
          province_id: res.data.province_id,
          city_id: res.data.city_id,
          district_id: res.data.district_id,
          detailNew: res.data.detailNew,
          id: res.data.id,
          city_name:res.data.city,
          district_name :res.data.area,
          province_name:res.data.province,
          town:res.data.town,
          town_id:res.data.town_id
          // region: region
        })
      }
    })

  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        that.setData({
          curChooseAddress: res.name ? res.name : res.address,
          curChooseLatitude: res.latitude,
          curChooseLongitude: res.longitude
        })
      },
      fail: (res) => {
        console.log('获取位置', res);
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.userLocation']) {
              that.setData({
                isShowsetting: true
              })
            } else {
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            }
          }
        })
      }
    })
  },
  hideSetting: function () {
    var that = this;
    that.setData({
      isShowsetting: false
    })
  },
  openSetting: function () {
    var that = this;
    that.hideSetting();
    wx.openSetting({
      success: (res) => {
        res.authSetting = {
          "scope.userLocation": true
        }
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  inputChange: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.setData({
      [type]: e.detail.value
    })
  },
  saveAddress: function () {
    var that = this;
    var region = that.data.region;
    var data = {};
    data.map = 'applet_address_add';
    data.name = that.data.name;
    data.mobile = that.data.mobile;
    data.address = that.data.addressdetail ? that.data.addressdetail : '';
    data.pro = that.data.province_name ? that.data.province_name : '';
    data.city = that.data.city_name ? that.data.city_name : '';
    data.area = that.data.district_name ? that.data.district_name : '';;
    // data.pro = that.data.curChooseAddress ? that.data.curChooseAddress:'';
    data.pcda = that.data.curChooseAddress ? that.data.curChooseAddress : '';
    data.lat = that.data.curChooseLatitude;
    data.lng = that.data.curChooseLongitude;
    data.code = that.data.code;
    data.id = that.data.id;
    //省市
    data.province_id = that.data.province_id ? that.data.province_id : '';
    data.city_id = that.data.city_id ? that.data.city_id : '';
    data.district_id = that.data.district_id ? that.data.district_id : '';
    data.town = that.data.town?that.data.town:'';
    data.town_id = that.data.town_id?that.data.town_id:'';
    if (!data.name) {
      app.errorTip(that, '请输入姓名', 2000);
      return;
    }
    if (!data.mobile) {
      app.errorTip(that, '请输入正确的手机号', 2000);
      return;
    }
    if(!data.province_id||!data.city_id||!data.district_id){
      app.errorTip(that, '请选择配送区域', 2000);
      return;
    }
    // if (!data.pcda) {
    //   app.errorTip(that, '请选择地址信息', 2000);
    //   return;
    // }
    // if (!data.pro || !data.city || !data.area) {
    //   app.errorTip(that, '请选择省市区', 2000);
    //   return;
    // }
    if (!data.address) {
      app.errorTip(that, '请输入详细地址', 2000);
      return;
    }
    console.log(data);
    //发起请求，获取列表列表
    wx.showLoading({
      title: '提交中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          console.log(that.data.operaType);
          if (that.data.operaType == 'waitorder' || that.data.operaType == "edit") {  // 订单编辑收货地址传的是edit，waitorder不晓得什么场景下使用的
            var curAddressData = res.data.data.address;
            // 存储当前编辑地址信息
            console.log("----------存储当前编辑地址信息",curAddressData);
            wx.getStorage({
              key: 'submitOrder',
              success: function (res) {
                console.log(res.data)
                var orderInfo = res.data;
                if(orderInfo.common) {
                  orderInfo.common.address = curAddressData;
                }else {
                  orderInfo.address = curAddressData;
                }
                
                wx.setStorage({
                  key: "submitOrder",
                  data: orderInfo,
                  success: function () {
                    wx.showToast({
                      title: '保存成功',
                      duration:1500
                    })
                    setTimeout(()=>{
                      wx.navigateBack({
                        delta: 1
                      })
                    },1500)
                    
                    console.log('更改后的地址更新-----');
                    console.log(orderInfo);
                  }
                })
              }
            })
          } else {
            wx.navigateBack({
              delta: 1
            })
          }
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  deleteAddress: function (e) {
    let that = this;
    var delId = e.target.dataset.editid;
    wx.showModal({
      title: '',
      content: '确认删除该收货地址吗？',
      confirmColor: '#1AAD16',
      success: function (res) {
        if (res.confirm) {
          //发起请求，获取列表列表
          wx.showLoading({
            title: '正在删除',
          })
          wx.request({
            url: app.globalData.requestUrl,
            data: {
              map: 'applet_address_delete',
              suid: app.globalData.suid,
              id: delId
            },
            success: function (res) {
              if (res.data.ec == 200) {
                console.log(res.data.data);
                wx.showModal({
                  title: '提示',
                  content: res.data.data.msg,
                  showCancel: false,
                  success: function () {
                    if(that.data.operaType == "edit"){
                      wx.getStorage({
                        key: 'submitOrder',
                        success(res){
                          var orderInfo = res.data;
                          
                          if(orderInfo.common) {
                            orderInfo.common.address = [];
                          }else {
                            orderInfo.address = [];
                          }
                          // data.common.totalPostFee = 0; //更新总运费
                          // orderInfo.common.total =Number((data.common.total-data.common.totalPostFee).toFixed(2));

                          wx.setStorage({
                            key: "submitOrder",
                            data: orderInfo,
                            success: function () {
                              wx.navigateBack({
                                delta: 1
                              })
                            }
                          })
                        }
                      })
                      return;
                    }
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                });
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.em,
                  showCancel: false
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onUnload: function () {
    wx.removeStorage({
      key: 'curEditaddress',
      success: function (res) {
        // console.log("清楚缓存成功")
      }
    })
  },
  GetAddress() {//获取地址
    let that = this
    let data = {
      map:'applet_address_get_by_pid',
      pid: 0
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      method:'GET',
      success: function(res) {
        that.setData({
          area:res.data.data
        })
      }
    })
  }
})